﻿#region 命名空间

using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Transactions;
using Microsoft.Practices.Unity.InterceptionExtension;

#endregion

namespace Sharp.Infrastructure.Crosscutting
{
    /// <summary>
    ///     事务处理器
    /// </summary>
    public class TransactionHandler : ICallHandler
    {
        /// <summary>
        ///     事务处理器
        /// </summary>
        public TransactionHandler()
        {
        }

        /// <summary>
        ///     构造函数，此处不可省略，否则会导致异常
        /// </summary>
        /// <param name="attributes">配置文件中所配置的参数</param>
        public TransactionHandler(NameValueCollection attributes)
        {
            Order = Convert.ToInt32(attributes["Order"]);
        }

        /// <summary>
        ///     排序
        /// </summary>
        public int Order { get; set; }

        /// <summary>
        ///     执行
        /// </summary>
        /// <param name="input"></param>
        /// <param name="getNext"></param>
        /// <returns></returns>
        [DebuggerStepThrough]
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            using (TransactionScope ts = new TransactionScope())
            {
                var result = getNext().Invoke(input, getNext);
                ts.Complete();
                return result;
            }
        }
    }
}